<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>扫狗游戏</title>
  <style>
    body {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      height: 100vh;
      background-image: url('https://i0.hdslb.com/bfs/new_dyn/defb5b38667a3e16675a80f72f69e4632141043022.png@.webp');
      background-size: cover;
      background-position: center;
      margin: 0;
      font-family: 'Arial', sans-serif;
      color: #333;
    }

    h1 {
      color: #ffffff;
      text-shadow: 2px 2px 5px rgba(0, 0, 0, 0.7);
    }

    .board-container {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 90vw; 
      height: 90vh; 
      overflow: hidden;
      background-color: rgba(255, 255, 255, 0.8);
      border-radius: 15px;
      box-shadow: 0 0 15px rgba(0, 0, 0, 0.5);
    }

    .board {
      display: grid;
      gap: 2px;
      width: 100%; 
      height: 100%; 
      max-width: 100%;
      max-height: 100%;
    }

    .cell {
      width: 100%;
      height: 100%;
      background-color: #ddd;
      text-align: center;
      line-height: 1;
      font-size: calc(1vw + 1vh);
      cursor: pointer;
      user-select: none;
      display: flex;
      justify-content: center;
      align-items: center;
      transition: background-color 0.3s, color 0.3s;
      box-shadow: 2px 2px 0px 0px #333, -2px -2px 0px 0px #333;
    }

    .cell:hover {
      background-color: #bbb;
    }

    .cell:active {
      background-color: #aaa;
    }

    .cell.revealed {
      background-color: #fff;
      cursor: default;
    }

    .cell.mine {
      background-color: red;
      color: white;
      font-weight: bold;
    }

    .cell.flagged {
      background-color: yellow;
      color: black;
    }

    .timer {
      font-size: 24px;
      margin-bottom: 10px;
      color: #ffffff;
      text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.7);
    }

    .difficulty-buttons {
      margin-bottom: 10px;
      display: flex;
      justify-content: center;
    }

    .difficulty-button {
      padding: 10px 20px;
      margin: 0 5px;
      border: none;
      border-radius: 5px;
      background-color: #555;
      color: white;
      cursor: pointer;
      font-size: 16px;
      transition: background-color 0.3s;
    }

    .difficulty-button:hover {
      background-color: #777;
    }

    .difficulty-button.active {
      background-color: #333;
    }

  </style>
</head>
<body>

<h1>扫狗游戏</h1>

<div class="difficulty-buttons">
  <button class="difficulty-button active" data-difficulty="easy">简单 (9x9, 10条狗)</button>
  <button class="difficulty-button" data-difficulty="medium">中等 (16x16, 40条狗)</button>
  <button class="difficulty-button" data-difficulty="hard">困难 (16x30, 99条狗)</button>
  <button class="difficulty-button" data-difficulty="fullscreen">全屏模式</button>
</div>

<div class="timer">时间: <span id="time">0</span> 秒</div>
<div class="board-container">
  <div class="board"></div>
</div>

<script>
  let boardSizeX;
  let boardSizeY;
  let mineCount;
  let board = [];
  let timerInterval;
  let secondsElapsed = 0;
  let leftMouseDown = false;
  let rightMouseDown = false;
  let revealedCount = 0; // 记录已经揭露的格子数量

  const boardElement = document.querySelector('.board');
  const boardContainer = document.querySelector('.board-container');
  const difficultyButtons = document.querySelectorAll('.difficulty-button');
  const timeElement = document.getElementById('time');

  // 根据难度设置网格尺寸和地雷数量
  function setDifficulty(difficulty) {
    switch (difficulty) {
      case 'easy':
        boardSizeX = 9;
        boardSizeY = 9;
        mineCount = 10;
        boardContainer.style.width = '50vw';
        boardContainer.style.height = '50vh';
        break;
      case 'medium':
        boardSizeX = 16;
        boardSizeY = 16;
        mineCount = 40;
        boardContainer.style.width = '70vw';
        boardContainer.style.height = '70vh';
        break;
      case 'hard':
        boardSizeX = 16;
        boardSizeY = 30;
        mineCount = 99;
        boardContainer.style.width = '90vw';
        boardContainer.style.height = '90vh';
        break;
      case 'fullscreen':
        boardSizeX = Math.floor(window.innerHeight / 30);
        boardSizeY = Math.floor(window.innerWidth / 30);
        mineCount = Math.floor((boardSizeX * boardSizeY) * 0.15);
        boardContainer.style.width = '90vw';
        boardContainer.style.height = '90vh';
        break;
    }
    initBoard();
  }

  function initBoard() {
    clearInterval(timerInterval);
    secondsElapsed = 0;
    timeElement.innerText = secondsElapsed;

    boardElement.style.gridTemplateColumns = `repeat(${boardSizeY}, 1fr)`;
    boardElement.style.gridTemplateRows = `repeat(${boardSizeX}, 1fr)`;

    board = Array.from({ length: boardSizeX }, () => Array(boardSizeY).fill(0));
    revealedCount = 0;
    let mines = [];

    while (mines.length < mineCount) {
      const x = Math.floor(Math.random() * boardSizeX);
      const y = Math.floor(Math.random() * boardSizeY);
      if (!mines.some(m => m.x === x && m.y === y)) {
        mines.push({ x, y });
        board[x][y] = -1;
      }
    }

    for (let x = 0; x < boardSizeX; x++) {
      for (let y = 0; y < boardSizeY; y++) {
        if (board[x][y] === -1) continue;
        board[x][y] = getMineCount(x, y);
      }
    }

    renderBoard();
    startTimer();
  }

  function getMineCount(x, y) {
    let count = 0;
    for (let i = -1; i <= 1; i++) {
      for (let j = -1; j <= 1; j++) {
        const nx = x + i;
        const ny = y + j;
        if (nx >= 0 && ny >= 0 && nx < boardSizeX && ny < boardSizeY) {
          if (board[nx][ny] === -1) count++;
        }
      }
    }
    return count;
  }

  function renderBoard() {
    boardElement.innerHTML = '';
    for (let x = 0; x < boardSizeX; x++) {
      for (let y = 0; y < boardSizeY; y++) {
        const cell = document.createElement('div');
        cell.classList.add('cell');
        cell.dataset.x = x;
        cell.dataset.y = y;
        cell.addEventListener('mousedown', handleMouseDown);
        cell.addEventListener('mouseup', handleMouseUp);
        cell.addEventListener('click', revealCell);
        cell.addEventListener('contextmenu', markCell);
        boardElement.appendChild(cell);
      }
    }
  }

  // 处理鼠标按下事件
  function handleMouseDown(event) {
    if (event.button === 0) leftMouseDown = true;
    if (event.button === 2) rightMouseDown = true;

    if (leftMouseDown && rightMouseDown) {
      doubleClickCell(event);
    }
  }

  // 处理鼠标松开事件
  function handleMouseUp(event) {
    if (event.button === 0) leftMouseDown = false;
    if (event.button === 2) rightMouseDown = false;
  }

  function doubleClickCell(event) {
    const x = parseInt(event.target.dataset.x);
    const y = parseInt(event.target.dataset.y);
    const cell = event.target;

    if (!cell.classList.contains('revealed')) return;

    const surroundingMines = board[x][y];
    const flaggedCount = countFlaggedMines(x, y);

    if (surroundingMines === flaggedCount) {
        let allFlagsCorrect = true;

        for (let i = -1; i <= 1; i++) {
            for (let j = -1; j <= 1; j++) {
                const nx = x + i;
                const ny = y + j;
                if (nx >= 0 && ny >= 0 && nx < boardSizeX && ny < boardSizeY) {
                    const adjacentCell = document.querySelector(`.cell[data-x="${nx}"][data-y="${ny}"]`);
                    if (adjacentCell.classList.contains('flagged') && board[nx][ny] !== -1) {
                        allFlagsCorrect = false;
                        break;
                    }
                }
            }
        }

        if (allFlagsCorrect) {
            for (let i = -1; i <= 1; i++) {
                for (let j = -1; j <= 1; j++) {
                    const nx = x + i;
                    const ny = y + j;
                    if (nx >= 0 && ny >= 0 && nx < boardSizeX && ny < boardSizeY) {
                        const adjacentCell = document.querySelector(`.cell[data-x="${nx}"][data-y="${ny}"]`);
                        if (!adjacentCell.classList.contains('flagged') && !adjacentCell.classList.contains('revealed')) {
                            revealCell({ target: adjacentCell });
                        }
                    }
                }
            }
        }
    }
  }

  function countFlaggedMines(x, y) {
    let count = 0;
    for (let i = -1; i <= 1; i++) {
      for (let j = -1; j <= 1; j++) {
        const nx = x + i;
        const ny = y + j;
        if (nx >= 0 && ny >= 0 && nx < boardSizeX && ny < boardSizeY) {
          const adjacentCell = document.querySelector(`.cell[data-x="${nx}"][data-y="${ny}"]`);
          if (adjacentCell.classList.contains('flagged')) count++;
        }
      }
    }
    return count;
  }

  function revealCell(event) {
    const x = parseInt(event.target.dataset.x);
    const y = parseInt(event.target.dataset.y);
    const cell = event.target;

    if (cell.classList.contains('revealed') || cell.classList.contains('flagged')) return;

    cell.classList.add('revealed');
    revealedCount++;

    if (board[x][y] === -1) {
      cell.classList.add('mine');
      alert('游戏结束！你踩到了狗狗！');
      clearInterval(timerInterval);
      disableBoard();
    } else if (board[x][y] > 0) {
      cell.textContent = board[x][y];
    } else {
      cell.textContent = '';
      for (let i = -1; i <= 1; i++) {
        for (let j = -1; j <= 1; j++) {
          const nx = x + i;
          const ny = y + j;
          if (nx >= 0 && ny >= 0 && nx < boardSizeX && ny < boardSizeY) {
            const adjacentCell = document.querySelector(`.cell[data-x="${nx}"][data-y="${ny}"]`);
            if (!adjacentCell.classList.contains('revealed')) {
              revealCell({ target: adjacentCell });
            }
          }
        }
      }
    }

    // 判断是否获胜
    if (revealedCount === (boardSizeX * boardSizeY - mineCount)) {
      clearInterval(timerInterval);
      setTimeout(() => {
        alert(`恭喜你赢了！用时 ${secondsElapsed} 秒！`);
      }, 100);
    }
  }

  function markCell(event) {
    event.preventDefault();
    const cell = event.target;
    if (cell.classList.contains('revealed')) return;

    if (cell.classList.contains('flagged')) {
      cell.classList.remove('flagged');
      cell.textContent = '';
    } else {
      cell.classList.add('flagged');
      cell.textContent = '🐕';
    }
  }

  function disableBoard() {
    const cells = document.querySelectorAll('.cell');
    cells.forEach(cell => {
      cell.removeEventListener('click', revealCell);
      cell.removeEventListener('contextmenu', markCell);
    });
  }

  function startTimer() {
    timerInterval = setInterval(() => {
      secondsElapsed++;
      timeElement.innerText = secondsElapsed;
    }, 1000);
  }

  difficultyButtons.forEach(button => {
    button.addEventListener('click', () => {
      difficultyButtons.forEach(btn => btn.classList.remove('active'));
      button.classList.add('active');
      setDifficulty(button.dataset.difficulty);
    });
  });

  setDifficulty('easy'); // 默认设置为简单难度

  window.addEventListener('resize', () => {
    if (boardElement.clientWidth > boardContainer.clientWidth || boardElement.clientHeight > boardContainer.clientHeight) {
      boardContainer.style.overflow = 'auto';
    } else {
      boardContainer.style.overflow = 'hidden';
    }
  });
</script>

</body>
</html>
